<?php
/**
 * QQAS - share your knowledge to the world!
 *
 * @author		xiaochong0302 <xiaochong0302@gmail.com>
 * @copyright	Copyright (c) 2011, Koogua Studio.
 * @license		http://www.qqas.org/user_guide/license.html
 * @link		http://www.qqas.org
 * @since		Version 1.0
 * @filesource
 */

// ------------------------------------------------------------------------

/**
 * 系统全局配置
 *
 * @category	Admin
 */
class ConfigAction extends AdminAction
{

	protected $Config;
	protected $jumpUrl;
	protected $configs;
	protected $boolRadios;
	protected $successMsg;
	

	// 初始化
	public function _initialize()
	{
		parent::_initialize();
		$this->Config  = D('Config');
		$this->configs = $this->Config->getConfigs();

		$this->boolRadios = array(1 => L('yes'), 0 => L('no'));
		$this->successMsg = L('msg.settings_updated');

		$this->assign('rs', $this->configs);
		$this->assign('jumpUrl', __URL__.'/'.ACTION_NAME);
	}


	// 基本设置
	public function general()
	{
		if ($this->isPost())
		{
		    $siteLogo = get_site_domain() . WEB_PUBLIC_PATH .'/Images/logo.gif';
			$data = array(
				'site_name'             => $_POST['site_name'],
				'site_url'              => trim(get_site_domain().dirname($_SERVER['SCRIPT_NAME']), '/'),
				'site_path'             => dirname($_SERVER['SCRIPT_FILENAME']),
				'site_logo'             => !empty($_POST['site_logo']) ? $_POST['site_logo'] : $siteLogo,
				'site_disable'          => $_POST['site_disable'],
				'site_disable_msg'      => $_POST['site_disable_msg'],
				'default_timezone'      => $_POST['default_timezone'],
				'default_dateformat'    => $_POST['default_dateformat'],
				'default_theme'         => $_POST['default_theme'],
				'default_lang'          => $_POST['default_lang'],
			);
			$this->Config->updateConfigs($data);
			$this->success($this->successMsg);
		}

		$dateformatOptions = array(
			0 => "d M Y, H:i",
			1 => "d M Y H:i",
			2 => "M jS, 'y, H:i",
			3 => "D M d, Y g:i a",
			4 => "F jS, Y, g:i a",
		);

		$this->assign('dateformatOptions', $dateformatOptions);
		$this->assign('dateformatSelected', $this->configs['default_dateformat']);

		$this->assign('timezoneOptions', L('timezone_options'));
		$this->assign('timezoneSelected', $this->configs['default_timezone']);

		$this->assign('langOptions', get_site_languages());
		$this->assign('langSelected', $this->configs['default_lang']);

		$this->assign('themeOptions', get_site_themes());
		$this->assign('themeSelected', $this->configs['default_theme']);

		$this->assign('siteDisableRadios', $this->boolRadios);
		$this->assign('siteDisableChecked', $this->configs['site_disable']);

		$this->display();
	}

	// 注册与访问
	public function register()
	{
		$UserGroup = D('UserGroup');
		
		if ($this->isPost())
		{
			$data = array(
				'register_enable'        => $_POST['register_enable'],
				'max_invites_per_week'   => intval($_POST['max_invites_per_week']),
				'invite_expiration'      => intval($_POST['invite_expiration']),
				'require_activation'     => $_POST['require_activation'],
				'require_protocol'       => $_POST['require_protocol'],
				'welcome_msg'            => $_POST['welcome_msg'],
				'max_ip_registration'    => intval($_POST['max_ip_registration']),
				'min_username_chars'     => intval($_POST['min_username_chars']),
				'max_username_chars'     => intval($_POST['max_username_chars']),
				'min_pwd_chars'          => intval($_POST['min_pwd_chars']),
				'max_pwd_chars'          => intval($_POST['max_pwd_chars']),
				'username_allowed_chars' => $_POST['username_allowed_chars'],
				'pwd_complex'            => $_POST['pwd_complex'],
			);
			
			$groups = $_POST['invite_allowed_groups'];
			if (!empty($groups))
			{
				$where = array('group_id' => array('in', $groups));
				$UserGroup->where($where)->setField('allow_invite', 1);
				$UserGroup->cacheUserGroup();
			}

			F('cache_registration_agreement', $_POST['reg_agreement_details']);

			$this->Config->updateConfigs($data);
			$this->success($this->successMsg);
		}
		
		
		$order = array('group_id' => 'asc');
		$userGroups = $UserGroup->order($order)->select();
		
		$this->assign('userGroups', $userGroups);

		$this->assign('registerEnableOptions', L('register.register_enable_options'));
		$this->assign('registerEnableChecked', $this->configs['register_enable']);
		
		$this->assign('requireActivationOptions', L('register.require_activation_options'));
		$this->assign('requireActivationChecked', $this->configs['require_activation']);
		
		$this->assign('usernameAllowedCharsOptions', L('register.username_allowed_chars_options'));
		$this->assign('usernameAllowedCharsSelected', $this->configs['username_allowed_chars']); 

		$this->assign('pwdComplexOptions', L('register.pwd_complex_options'));
		$this->assign('pwdComplexSelected', $this->configs['pwd_complex']); 

		$this->assign('welcomeMsgRadios',$this->boolRadios);
		$this->assign('welcomeMsgChecked', $this->configs['welcome_msg']);

		$this->assign('regAgreementRadios', $this->boolRadios);
		$this->assign('regAgreementChecked', $this->configs['require_reg_agreement']);
		$this->assign('regAgreementDetails',  F('cache_registration_agreement'));

		$this->display();
	}


	//优化设置
	public function optimize()
	{
		if ($this->isPost())
		{
			if ($_POST['allow_gzip'] && !extension_loaded('zlib'))
			{
				$this->error(L('msg_gzip_invalid'));
			}

			$data = array(
			    'url_format_type'    => $_POST['url_format_type'],
			    'url_word_seperator' => $_POST['url_word_seperator'],
				'site_slogan'        => $_POST['site_slogan'],
				'site_keywords'      => $_POST['site_keywords'],
				'site_description'   => $_POST['site_description'],
				'site_head_others'   => $_POST['site_head_others'],

				'gzip_enable'        => $_POST['gzip_enable'],
				'lazy_update_enable' => $_POST['lazy_update_enable'],
				'load_limit'         => intval($_POST['load_limit']),

				'max_online_users'   => intval($_POST['max_online_users']),
				'online_hold_time'   => intval($_POST['online_hold_time']),

				'cache_home_page_expiration' => intval($_POST['cache_home_page_expiration']),
				'cache_question_page_expiration' => intval($_POST['cache_question_page_expiration']),
			);

			$this->Config->updateConfigs($data);
			$this->success($this->successMsg);

		}

		$this->assign('urlFormatTypeRadios', L('optimize.url_format_type_options'));
		$this->assign('urlFormatTypeChecked', $this->configs['url_format_type']);

		$this->assign('urlWordSeperatorRadios', L('optimize.url_word_seperator_options'));
		$this->assign('urlWordSeperatorChecked', $this->configs['url_word_seperator']);

		$this->assign('gzipRadios', $this->boolRadios);
		$this->assign('gzipChecked', $this->configs['gzip_enable']);

		$lazyUpdateRadios = $this->boolRadios;
		$this->assign('lazyUpdateRadios', $this->boolRadios);
		$this->assign('lazyUpdateChecked', $this->configs['lazy_update_enable']);

		$this->display();
	}

	//邮件服务设置
	public function email()
	{
		if ($this->isPost())
		{
			$data = array(
			    'return_email'        => $_POST['return_email'],
				'contact_email'       => $_POST['contact_email'],
				'email_signature'     => $_POST['email_signature'],
				'mailer_type'         => $_POST['mailer_type'],
				'smtp_host'           => $_POST['smtp_host'],
				'smtp_port'           => $_POST['smtp_port'],
				'smtp_encrypt'        => $_POST['smtp_encrypt'],
				'smtp_auth'           => $_POST['smtp_auth'],
				'smtp_auth_username'  => $_POST['smtp_auth_username'],
				'smtp_auth_password'  => $_POST['smtp_auth_password'],

			);
			$this->Config->updateConfigs($data);
			$this->success($this->successMsg);
		}

		$mailerTypeRadios = array(
			'mail' => L('email.mailer_type_1'),
			'smtp' => L('email.mailer_type_2'),
		);
		$this->assign('mailerTypeRadios', $mailerTypeRadios);
		$this->assign('mailerTypeChecked', $this->configs['mailer_type']);

		$encryptRadios = array(
		   'null' => L('none'),
		   'ssl'  => L('email.smtp_encrypt_ssl'),
		   'tls'  => L('email.smtp_encrypt_tls'),
		);
		$this->assign('encryptRadios', $encryptRadios);
		$this->assign('encryptChecked', $this->configs['smtp_encrypt']);

		$this->assign('authRadios', $this->boolRadios);
		$this->assign('authChecked', $this->configs['smtp_auth']);

		$this->display();
	}


	//邮件模板
	public function emailTemplate()
	{
        $Template = D('EmailTemplate');
        
		$identifier = isset($_REQUEST['identifier']) ? $_REQUEST['identifier'] : '';
		$language = isset($_REQUEST['language']) ? $_REQUEST['language'] : 'en-us';

		$this->assign('jumpUrl', __ACTION__.'/identifier/'.$identifier.'/language/'.$language);

		if ($this->isPost())
		{
			if (false == $Template->create())
			{
				$this->error($Template->getError());
			}
			$data = array(
				'identifier' => $_POST['identifier'],
				'subject'    => $_POST['subject'],
				'message'    => $_POST['message'],
				'type'       => 'template',
				'language'   => $_POST['language'],
				'edit_time'  => time(),
			);
			$Template->replace($data);
			$Template->cacheEmailTemplates();
			$this->success(L('email.tpl_updated_succeed'));
		}
		else
		{
			$map = array('language' => 'en-us');
			$templateList = $Template->where($map)->select();
			if ($identifier && $language)
			{
				$where  = array('identifier' => $identifier, 'language' => $language);
				$result = $Template->where($where)->find();
				if (empty($result))
				{
					$where  = array('identifier' => $identifier, 'language' => 'en-us');
					$result = $Template->where($where)->find();
				}
			}
			else
			{
				$result = $Template->where($map)->find();
			}

			$this->assign('langOptions', get_site_languages());
			$this->assign('langSelected', $language);

			$this->assign('templateList', $templateList);
			$this->assign('rs', $result);
			$this->display();
		}
	}


	// 功能设置
	public function feature()
	{
		if ($this->isPost())
		{
		    $clientIP = get_client_ip();
            if (!empty($_POST['acp_ip_whitelist']))
            {
                $flag = FALSE;
            	$whitelist = explode("\r\n", $_POST['acp_ip_whitelist']);
            	foreach ($whitelist as $value)
            	{
            		if (preg_match('/^'.preg_quote($value).'/', $clientIP))
            		{
            			$flag = TRUE;
            			break;
            		}
            	}
            	if (!$flag)
            	{
            	    $msg = sprintf(L('msg.admin_ip_not_in_whitelist'), $clientIP);
            		$this->error($msg);
            	}
            }

			$data = array(
			    'markup_mode'             => $_POST['markup_mode'],
			    'question_expiration'     => intval($_POST['question_expiration']),
			    'vote_expiration'         => intval($_POST['vote_expiration']),
			    'min_title_chars'         => intval($_POST['min_title_chars']),
			    'max_title_chars'         => intval($_POST['max_title_chars']),
			    'min_post_chars'          => intval($_POST['min_post_chars']),
                'max_post_chars'          => intval($_POST['max_post_chars']),
                'max_post_tags'           => intval($_POST['max_post_tags']),
			    'max_post_links'          => intval($_POST['max_post_links']),
				'word_censor_enable'            => $_POST['word_censor_enable'], 
				'comment_on_question_enable'    => $_POST['comment_on_question_enable'],
				'comment_on_answer_enable'      => $_POST['comment_on_answer_enable'],
				'close_expired_question_enable' => $_POST['close_expired_question_enable'],			
			    
			    'create_team_enable'         => $_POST['create_team_enable'],
			    'max_creatable_teams'        => intval($_POST['max_creatable_teams']),
			    'max_joinable_teams'         => intval($_POST['max_joinable_teams']),
				'answer_revision_enable'     => $_POST['answer_revision_enable'], 
				'allow_team_rename'          => $_POST['allow_team_rename'], 
				'allow_team_recategorize'    => $_POST['allow_team_recategorize'], 
			    
                'tag_enable'                 => $_POST['tag_enable'],
				'feed_enable'                => $_POST['feed_enable'],
				'feed_fulltext_enable'       => $_POST['feed_fulltext_enable'],
				'max_feed_items'             => intval($_POST['max_feed_items']),
				'feed_rss_ttl'               => intval($_POST['feed_rss_ttl']),

				'google_analytics_enable'    => $_POST['google_analytics_enable'],
				'google_ua_code'             => $_POST['google_ua_code'],
                'google_site_search_enable'  => $_POST['google_site_search_enable'],

				'bot_enable'                 => $_POST['bot_enable'],
				'recycle_bin_enable'         => $_POST['recycle_bin_enable'],

				'form_token_enable'          => $_POST['form_token_enable'],
				'email_check_mx_enable'      => $_POST['email_check_mx_enable'],
				'max_login_attempts'         => intval($_POST['max_login_attempts']),
				'jump_wait_time'             => $_POST['jump_wait_time'],
				'acp_ip_whitelist'           => $_POST['acp_ip_whitelist'],
			);
			$this->Config->updateConfigs($data);
			$this->success($this->successMsg);
		}

		$this->assign('markupModeRadios', L('feature.markup_mode_options'));
		$this->assign('markupModeChecked', $this->configs['markup_mode']);

		$this->assign('createTeamEnableRadios', $this->boolRadios);
		$this->assign('createTeamEnableChecked', $this->configs['create_team_enable']);
		
		$this->assign('answerRevisionEnableRadios', $this->boolRadios);
		$this->assign('answerRevisionEnableChecked', $this->configs['answer_revision_enable']);
		
		$this->assign('allowTeamRenameRadios', $this->boolRadios);
		$this->assign('allowTeamRenameChecked', $this->configs['allow_team_rename']);
		
		$this->assign('allowTeamRecategorizeRadios', $this->boolRadios);
		$this->assign('allowTeamRecategorizeChecked', $this->configs['allow_team_recategorize']);
		
		$this->assign('tagEnableRadios', $this->boolRadios);
		$this->assign('tagEnableChecked', $this->configs['tag_enable']);
		
		$this->assign('commentOnQuestionEnableRadios', $this->boolRadios);
		$this->assign('commentOnQuestionEnableChecked', $this->configs['comment_on_question_enable']);
		
		$this->assign('commentOnAnswerEnableRadios', $this->boolRadios);
		$this->assign('commentOnAnswerEnableChecked', $this->configs['comment_on_answer_enable']);

		$this->assign('wordCensorEnableRadios', $this->boolRadios);
		$this->assign('wordCensorEnableChecked', $this->configs['word_censor_enable']);

		$this->assign('closeExpiredQuestionEnableRadios', $this->boolRadios);
		$this->assign('closeExpiredQuestionEnableChecked', $this->configs['close_expired_question_enable']);
		
		$this->assign('recycleBinEnableRadios', $this->boolRadios);
		$this->assign('recycleBinEnableChecked', $this->configs['recycle_bin_enable']);

		$this->assign('botEnableRadios', $this->boolRadios);
		$this->assign('botEnableChecked', $this->configs['bot_enable']);

		$this->assign('feedEnableRadios', $this->boolRadios);
		$this->assign('feedEnableChecked', $this->configs['feed_enable']);
		
		$this->assign('feedFulltextEnableRadios', $this->boolRadios);
		$this->assign('feedFulltextEnableChecked', $this->configs['feed_fulltext_enable']);

		$this->assign('googleAnalyticsEnableRadios', $this->boolRadios);
		$this->assign('googleAnalyticsEnableChecked', $this->configs['google_analytics_enable']);

		$this->assign('googleSiteSearchEnableRadios', $this->boolRadios);
		$this->assign('googleSiteSearchEnableChecked', $this->configs['google_site_search_enable']);

		$this->assign('formTokenEnableRadios', $this->boolRadios);
		$this->assign('formTokenEnableChecked', $this->configs['form_token_enable']);

		$this->assign('emailCheckMxEnableRadios', $this->boolRadios);
		$this->assign('emailCheckMxEnableChecked', $this->configs['email_check_mx_enable']);
		
		$this->display();
	}


	// 显示设置
	function displaying()
	{
	     if ($this->isPost())
		{
			$data = array(

                'display_links'           => $_POST['display_links'],
				'display_category_count'  => $_POST['display_category_count'],
				'display_last_edited'     => $_POST['display_last_edited'],
				'runtime_enable'          => $_POST['runtime_enable'],

			    'questions_per_page'      => intval($_POST['questions_per_page']),
			    'answers_per_page'        => intval($_POST['answers_per_page']),
                'users_per_page'          => intval($_POST['users_per_page']),
                'tags_per_page'           => intval($_POST['tags_per_page']),
                'teams_per_page'          => intval($_POST['teams_per_page']),

                'max_question_pages'      => intval($_POST['max_question_pages']),
                'max_user_pages'          => intval($_POST['max_user_pages']),
                'hot_tag_size'            => intval($_POST['hot_tag_size']),
                'history_size'            => intval($_POST['history_size']),
                'top_user_size'           => intval($_POST['top_user_size']),
                'related_question_size'   => intval($_POST['related_question_size']),
			);
			$this->Config->updateConfigs($data);
			$this->success($this->successMsg);
		}

		$this->assign('lastEditedRadios', $this->boolRadios);
		$this->assign('lastEditedChecked', $this->configs['display_last_edited']);

		$this->assign('linksRadios', $this->boolRadios);
		$this->assign('linksChecked', $this->configs['display_links']);

		$this->assign('cateCountRadios', $this->boolRadios);
		$this->assign('cateCountChecked', $this->configs['display_category_count']);

		$this->assign('runtimeRadios', $this->boolRadios);
		$this->assign('runtimeChecked', $this->configs['runtime_enable']);

		$this->display();
	}


	//积分设置
	function point()
	{
		if ($this->isPost())
		{
			$policy = array(
				'ask'                 => intval($_POST['point_ask']),
				'urgent'              => intval($_POST['point_urgent']),
				'answer'              => intval($_POST['point_answer']),
				'login'               => intval($_POST['point_login']),
				'register'            => intval($_POST['point_register']),
				'invite'              => intval($_POST['point_invite']),
				'vote'                => intval($_POST['point_vote']),
				'choose_best_answer'  => intval($_POST['point_choose_best_answer']),
				'best_answer'         => intval($_POST['point_selected_as_best_answer']),
				'no_best_answer'      => intval($_POST['point_no_best_answer']),
				'delete_answer'       => intval($_POST['point_delete_answer']),
			);
			$data = array('point_policy' => serialize($policy));
			$this->Config->updateConfigs($data);
			$this->success($this->successMsg);
		}
		$policy = unserialize($this->configs['point_policy']);
		$this->assign('policy', $policy);
		$this->display();
	}


	// 头像设置
	function avatar()
	{
	    if ($this->isPost())
	    {
	    	$data = array('gravatar_parameters' => serialize($_POST['gravatar']));
        	$this->Config->updateConfigs($data);
			$this->success($this->successMsg);
	    }

	    $gravatar = unserialize($this->configs['gravatar_parameters']);
	    $this->configs['gravatar'] = $gravatar;

		$this->assign('gravatarRatingOptions', L('avatar.gravatar_rating_options'));
		$this->assign('gravatarRatingChecked', $gravatar['rating']);

		$this->assign('gravatarDefaultOptions',L('avatar.gravatar_default_options'));
		$this->assign('gravatarDefaultChecked', $gravatar['default']);

		$this->assign('rs', $this->configs);
		$this->display();
	}


	// 验证码设置
	function captcha()
	{
	    if ($this->isPost())
	    {
	    	$data = array(
        		'captcha_when'          => serialize($_POST['captcha_when']),
        		'captcha_parameters'    => serialize($_POST['captcha_parameters']),
        		'group_without_captcha' => implode(',', $_POST['group_without_captcha']),
        	);
        	$this->Config->updateConfigs($data);
			$this->success($this->successMsg);
	    }

	    $parameters  = unserialize($this->configs['captcha_parameters']);
	    $captchaWhen = unserialize($this->configs['captcha_when']);
	    $this->configs['captcha_parameters'] = $parameters;
        $this->configs['captcha_when'] = $captchaWhen;

	    $charTypeRadios = array(
		   'number' => L('captcha.char_type_number'),
		   'letter' => L('captcha.char_type_letter'),
		   'alphanumeric' => L('captcha.char_type_alphanumeric'),
		);
        $this->assign('charTypeRadios', $charTypeRadios);
		$this->assign('charTypeChecked', $parameters['char_type']);

		$imageTypeRadios = array(
		   'gif' => L('captcha.image_type_gif'),
		   'jpeg' => L('captcha.image_type_jpg'),
		   'png' => L('captcha.image_type_png'),
		);
        $this->assign('imageTypeRadios', $imageTypeRadios);
		$this->assign('imageTypeChecked', $parameters['image_type']);

		$this->assign('registerCaptchaRadios', $this->boolRadios);
		$this->assign('registerCaptchaChecked', $captchaWhen['register']);

		$this->assign('loginCaptchaRadios', $this->boolRadios);
		$this->assign('loginCaptchaChecked', $captchaWhen['login']);

		$this->assign('postCaptchaRadios', $this->boolRadios);
		$this->assign('postCaptchaChecked', $captchaWhen['post']);

		$this->assign('reportCaptchaRadios', $this->boolRadios);
		$this->assign('reportCaptchaChecked', $captchaWhen['report']);

		$this->assign('emailCaptchaRadios', $this->boolRadios);
		$this->assign('emailCaptchaChecked', $captchaWhen['email']);

		$Group = D('UserGroup');
		$userGroupList = $Group->select();
		$this->assign('userGroupList', $userGroupList);

		$this->assign('rs', $this->configs);
		$this->display();
	}


	// 登录认证
	function auth()
	{
	    if ($this->isPost())
		{
			$data = array(
				'openid_auth_enable'         => $_POST['openid_auth_enable'],
				'myopenid_account_enable'    => $_POST['myopenid_account_enable'],
				'aol_account_enable'         => $_POST['aol_account_enable'],
				'yahoo_account_enable'       => $_POST['yahoo_account_enable'],
				'google_account_enable'      => $_POST['google_account_enable'],
				'twitter_account_enable'     => $_POST['twitter_account_enable'],
				'facebook_account_enable'    => $_POST['facebook_account_enable'],
				'facebook_appid'             => $_POST['facebook_appid'],
				'facebook_secret'            => $_POST['facebook_secret'],
				'twitter_key'                => $_POST['twitter_key'],
				'twitter_secret'             => $_POST['twitter_secret'],
			);
			$this->Config->updateConfigs($data);
			$this->success($this->successMsg);
		}

		$this->assign('facebookRadios', $this->boolRadios);
		$this->assign('facebookChecked', $this->configs['facebook_account_enable']);

		$this->assign('twitterRadios', $this->boolRadios);
		$this->assign('twitterChecked', $this->configs['twitter_account_enable']);

		$this->assign('googleRadios', $this->boolRadios);
		$this->assign('googleChecked', $this->configs['google_account_enable']);

		$this->assign('yahooRadios', $this->boolRadios);
		$this->assign('yahooChecked', $this->configs['yahoo_account_enable']);

		$this->assign('aolRadios', $this->boolRadios);
		$this->assign('aolChecked', $this->configs['aol_account_enable']);

		$this->assign('myopenidRadios', $this->boolRadios);
		$this->assign('myopenidChecked', $this->configs['myopenid_account_enable']);

		$this->display();
	}


	// 搜索设置
	function search()
	{
	    if ($this->isPost())
		{
			$data = array(
				'search_user_interval'    => intval($_POST['search_user_interval']),
				'search_guest_interval'   => intval($_POST['search_guest_interval']),
				'search_min_chars'        => intval($_POST['search_min_chars']),
				'search_max_chars'        => intval($_POST['search_max_chars']),
				'search_max_results'      => intval($_POST['search_max_results']),
			);
			$this->Config->updateConfigs($data);
			$this->success($this->successMsg);
		}
		$this->display();
	}

}
// End  Settings Class

/* End of file ConfigAction.class.php */
/* Location: ./App/Lib/Action/Admin/ConfigAction.class.php */